<script setup lang="ts" name="PanelCompensation">
import { mapState } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { isCompensationSupported } from '../../utils/bpmnPropertyUtils/eventDefinition'
import { getWaitForCompletionValue, setWaitForCompletionValue, getActivityRef, setActivityRef, getActivityOptions } from '../../utils/compensation'
import EventEmitter from '@/utils/EventEmitter'

const form = ref({
  waitForCompletion: false,
  id: ''
})

const mapStates = computed(() => {
  return mapState(useModelerStore, ['getActive'])
})

const activityOptions = ref([])

const waitForCompletionChange = (v) => {
  setWaitForCompletionValue(mapStates.value.getActive(), v)
}

const activityChange = (v) => {
  setActivityRef(mapStates.value.getActive(), v)
}

const initData = () => {
  form.value.waitForCompletion = getWaitForCompletionValue(mapStates.value.getActive())
  form.value.id = getActivityRef(mapStates.value.getActive())
  activityOptions.value = getActivityOptions(mapStates.value.getActive())
}

const eventEmitterListener = () => {
  if (isCompensationSupported(mapStates.value.getActive())) {
    initData()
  }
}

onBeforeUnmount(() => {
  EventEmitter.removeListener('element-update', eventEmitterListener)
})

onMounted(() => {
  initData()
  EventEmitter.on('element-update', eventEmitterListener)
})
</script>

<template>
  <el-collapse-item name="compensation">
    <template #title>
      <div class="collapse-header">
        <svg-icon icon="ri:remixicon-fill"></svg-icon>
        <h2>补偿</h2>
      </div>
    </template>
    <el-form-item label="等待完成">
      <el-switch v-model="form.waitForCompletion" @change="waitForCompletionChange" />
    </el-form-item>
    <el-form-item label="活动参考">
      <el-select v-model="form.id" clearable @change="activityChange">
        <el-option v-for="item in activityOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
  </el-collapse-item>
</template>

<style scoped lang="scss">
.el-collapse-item {
  :deep(.el-collapse-item__header) {

    .collapse-header {
      display: flex;
      flex: 1;
      align-items: center;
      padding: 0 12px;

      .el-icon {
        margin-right: 6px;
        font-size: 20px !important;
      }

      h2 {
        font-weight: bold;
        font-size: 14px;
      }
    }

    .el-icon {
      font-size: 18px;
    }
  }

  :deep(.el-collapse-item__content) {
    padding-right: 12px;
    padding-bottom: 12px;
    padding-left: 12px;
  }
}
</style>
